package com.cloudcc.mobile.view.main;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.EventList.MenuFillEvent;
import com.cloudcc.cloudframe.bus.EventList.UpdateUserEvent;
import com.cloudcc.cloudframe.bus.IEventLife;
import com.cloudcc.cloudframe.bus.MenuToggleEvent;
import com.cloudcc.cloudframe.model.MenuModel;
import com.cloudcc.cloudframe.model.MenuTabModel;
import com.cloudcc.cloudframe.model.UserModel;
import com.cloudcc.cloudframe.util.ListUtils;
import com.cloudcc.cloudframe.util.LogUtils;
import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.AppManager;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.adapter.MenuAdapter;
import com.cloudcc.mobile.adapter.MyMenuAdapter;
import com.cloudcc.mobile.db.ApprovalDB;
import com.cloudcc.mobile.db.ChatMessageDB;
import com.cloudcc.mobile.db.DraftBoxDB;
import com.cloudcc.mobile.db.EventDB;
import com.cloudcc.mobile.db.MessageDB;
import com.cloudcc.mobile.db.TaskDB;
import com.cloudcc.mobile.entity.CoworkerEntity;
import com.cloudcc.mobile.entity.ModuleMessage;
import com.cloudcc.mobile.im.IMHelper;
import com.cloudcc.mobile.im.utils.PreferenceManager;
import com.cloudcc.mobile.manager.CacheManager;
import com.cloudcc.mobile.manager.CloudCCPushManager;
import com.cloudcc.mobile.manager.ConfigManager;
import com.cloudcc.mobile.manager.ContactsManager;
import com.cloudcc.mobile.manager.MenuManager;
import com.cloudcc.mobile.manager.OrmManager;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.presenter.MainUIPresenter;
import com.cloudcc.mobile.presenter.UserPresenter;
import com.cloudcc.mobile.service.BindingService;
import com.cloudcc.mobile.service.DingWeiService;
import com.cloudcc.mobile.util.DialogUtils;
import com.cloudcc.mobile.util.FileUtil;
import com.cloudcc.mobile.util.ImageUtils;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.util.UrlTools;
import com.cloudcc.mobile.util.UserUtils;
import com.cloudcc.mobile.view.activity.MapsActivity;
import com.cloudcc.mobile.view.activity.SelectPicActivity;
import com.cloudcc.mobile.view.activity.SelectPictureActivity;
import com.cloudcc.mobile.view.base.BaseActivity;
import com.cloudcc.mobile.view.dynamic.SendTimeLineActivity;
import com.cloudcc.mobile.view.dynamic.dynamic.DynamicMainFragment;
import com.cloudcc.mobile.view.main.fragment.CoworkerListFragment;
import com.cloudcc.mobile.view.main.fragment.MainMeFragment;
import com.cloudcc.mobile.view.main.fragment.MainMessageFragment;
import com.cloudcc.mobile.view.main.fragment.MainUIFragment;
import com.cloudcc.mobile.view.main.fragment.SettingFragment;
import com.cloudcc.mobile.view.wel.WelcomeActivity;
import com.cloudcc.mobile.weight.MyExpandableListView;
import com.dk.view.drop.CoverManager;
import com.easemob.EMCallBack;
import com.easemob.EMEventListener;
import com.easemob.EMNotifierEvent;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMGroupManager;
import com.easemob.chat.EMMessage;
import com.lidroid.xutils.exception.DbException;
import com.slidingmenu.lib.SlidingMenu;
import com.umeng.update.UmengDialogButtonListener;
import com.umeng.update.UmengUpdateAgent;
import com.umeng.update.UpdateStatus;

/**
 * 主页
 * 
 * @author wangzhiqiang
 * @date 2015-6-15 下午1:11:39
 * 
 */
/**
 * @author seven
 * 
 */
@SuppressLint("SetJavaScriptEnabled")
public class MainUIActivity extends BaseActivity implements
		OnChildClickListener, IEventLife, OnClickListener, EMEventListener {
	private LinearLayout contaxt, me, xiaoxi, zhuye,
			footer_cooperation_container;
	private LinearLayout menu_foot;
	private ImageView contaxt_image, locationImg, photoimag, me_image,
			xiaoxi_image, index_image, zhuye_img, footer_cooperation_icon;
	private TextView phototext, qiandaotext, messagenum, tvCompanyName,
			contaxt_text, tvUserName, me_Text, xiaoxi_Text, zhuye_text,
			footer_cooperation_text;
	private ImageView menuUserLogo;
	private List<Fragment> fragments = new ArrayList<Fragment>();
	private ArrayList<ModuleMessage> list;
	private MenuAdapter adapter;
	private MyMenuAdapter mMenuAdapter;
	private SlidingMenu menu;
	private String picPath;
	private int currentTab = -1;

	private MyMessageReceiver receiver;
	public Bitmap photo, imgphoto;
	private LinearLayout menuSetting, menuHome;
	private TextView menu_index_name;

	/**
	 * slidemenu 下面的菜单
	 */
	MyExpandableListView module_list;
	private long num;
	private WebView webview;
	private int mGroupPosition = -101;
	private int mChildPosition = -102;
	int expandFlag = -100;// 控制列表的展开
	private int sign = -1;// 控制group只能打开一个

	private MainUIPresenter mPresenter = new MainUIPresenter();
	private UserPresenter userPresenter = new UserPresenter();

	private MenuModel ccMenu;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		register();
		mActivityFrom = getIntent().getIntExtra("activity.from", -1);
		try {
			initCoverManager();// 信息提示气泡管理器
		} catch (Exception e) {
		}
		try {
			initMenu();
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			setMessageNum();
			initPushAndLocat();
		} catch (Exception e) {
			Tools.handle(e);
		}
		try {
			isFenxiang();// 是否分享
			initPage();
			addListener();
			tvUserName.setText(UserManager.getManager().getUser().userName);
			tvCompanyName.setText(UserManager.getManager().getUser().orgName);
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 登录小网页 test 暂时每次都登录
		if (mActivityFrom==2) {
			loginWebView();
		}
		
		// 聊天IM
		loginIM();

		// 登陆成功了 设置 不是第一次登录
		UserManager.getManager().saveFrist(false);
		
		initUpdate();
		
	}
	private void initUpdate(){
		UmengUpdateAgent.setUpdateOnlyWifi(false);
		UmengUpdateAgent.setDeltaUpdate(false);
		UmengUpdateAgent.setDialogListener(new UmengDialogButtonListener() {
			@Override
			public void onClick(int status) {
		        switch (status) {
		        case UpdateStatus.NotNow:
		        	AppManager.getInstance().AppExitOld();
		        	AppManager.getInstance().AppExit();
		            break;
		        }
				
			}
		});
		UmengUpdateAgent.update(this);
	}

	public void onEventMainThread(UpdateUserEvent event) {
		String message = "更换头像";
		if (event.isOk()) {
			message += "成功";
		} else {
			message += "失败";
		}

		Toast.makeText(mContext, message, 0).show();
	}

	private void fillUser() {
		tvCompanyName.setText(UserManager.getManager().getUser().orgName);
		String userId = UserManager.getManager().getUser().userId;
		String url = UrlTools.getTopImage(userId);
		UserUtils.setLogoRound(url, menuUserLogo,
				UserUtils.getBackGroudColorByUserIdHash(userId, mContext),
				UserUtils.getNickRowName(UserManager.getManager().getUser().userName), mContext);
	}

	public void onEventMainThread(MenuToggleEvent event) {
		if (menu == null) {
			return;
		}
		if (event.isToggle) {
			if (event.open) {
			}
		} else {
			menu.toggle();
		}
	}

	@Override
	public int getLayoutId() {
		return R.layout.act_main;
	}

	/**
	 * 初始化 消息提示
	 */
	private void initCoverManager() {
		// 消息条数的提示 消息清除动画
		CoverManager.getInstance().init(this);
		CoverManager.getInstance().setMaxDragDistance(150);
		CoverManager.getInstance().setExplosionTime(150);
	}

	/**
	 * 是否是分享
	 */
	private void isFenxiang() {
		if (AppContext.isFenXiang) {
			Intent intent = new Intent(this, SendTimeLineActivity.class);
			startActivity(intent);
		}
	}


	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// super.onSaveInstanceState(outState);
	}

	private void addListener() {
		/**
		 * 点击签到
		 */
		qiandaotext.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainUIActivity.this,
						MapsActivity.class);
				startActivity(intent);
				menu.toggle();
			}
		});
		/**
		 * 改变头像
		 */
		photoimag.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainUIActivity.this,
						SelectPictureActivity.class);
				startActivityForResult(intent, 70);
			}
		});
		/**
		 * 签到
		 */
		locationImg.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainUIActivity.this,
						MapsActivity.class);
				startActivity(intent);
				menu.toggle();
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK && requestCode == 70) {
			// imageView不设null, 第一次上传成功后，第二次在选择上传的时候会报错。
			picPath = data.getStringExtra(SelectPicActivity.KEY_PHOTO_PATH);
			File temp = new File(picPath);
			startPhotoZoom(Uri.fromFile(temp));
		} else if (resultCode == Activity.RESULT_OK&&requestCode == 3) {
			menuUserLogo.setImageBitmap(null);
			if (data != null) {
				Bundle extras = data.getExtras();
				if (extras != null) {
					photo = extras.getParcelable("data");
					imgphoto = ImageUtils.toRoundBitmap(photo);
					menuUserLogo.setImageBitmap(imgphoto);
					UserManager.getManager().saveLogo(photo);
					userPresenter.UpdateLogo(photo, UserManager.getManager()
							.getUser());
				}
			} else {
				byte[] imagebyte = ImageUtils.readSdcard(picPath);
				photo = ImageUtils.loadBitmap(imagebyte, 100, 100);
				imgphoto = ImageUtils.toRoundBitmap(photo);
				menuUserLogo.setImageBitmap(imgphoto);
				userPresenter.UpdateLogo(photo, UserManager.getManager()
						.getUser());
			}
		}
	}

	// 初始化菜单
	private void initMenu() {
		menu = new SlidingMenu(this);
		menu.setMode(SlidingMenu.LEFT);
		menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN); // 触摸边界拖出菜单
		menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
		menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);

		View view = LayoutInflater.from(this).inflate(R.layout.menu_item_new,
				null);
		menu.setMenu(view);
		menuUserLogo = (ImageView) view.findViewById(R.id.userimg);
		menuUserLogo.setOnClickListener(this);
		tvUserName = (TextView) view.findViewById(R.id.name);
		tvCompanyName = (TextView) view.findViewById(R.id.menu_gongsi);
		phototext = (TextView) view.findViewById(R.id.phototext);
		phototext.setOnClickListener(this);
		qiandaotext = (TextView) view.findViewById(R.id.qiandaotext);
		tvCompanyName = (TextView) view.findViewById(R.id.menu_gongsi);
		photoimag = (ImageView) view.findViewById(R.id.titleimag);
		locationImg = (ImageView) view.findViewById(R.id.locationImg);

		menuHome = (LinearLayout) view.findViewById(R.id.shouye_menu);// 首页按钮
		menuHome.setOnClickListener(this);
		menuSetting = (LinearLayout) view.findViewById(R.id.shezhi_menu);
		menuSetting.setOnClickListener(this);
		module_list = (MyExpandableListView) view
				.findViewById(R.id.module_list);
		menu_index_name = (TextView) view.findViewById(R.id.menu_index_name);
		
		fillUser();
		
		requestFromCache();
		requestFromNet();
	}
	
	/**
	 * 从本地获取
	 */
	private void requestFromCache(){
		List<MenuModel> menus = CacheManager.getInstance().getMenu();
		if (!ListUtils.isEmpty(menus)) {
			fillMenu(false, menus);
		}
		
	}
	/**
	 * 从网络获取
	 */
	private void requestFromNet(){
		mPresenter.getMenus();
	}

	private TextView drop;

	/**
	 * 获取控件
	 * 
	 * @throws DbException
	 */
	private void initPage() {
		fragments.add(new MainUIFragment());
		fragments.add(new MainMessageFragment());
		fragments.add(new DynamicMainFragment());
		fragments.add(new CoworkerListFragment());
		fragments.add(new MainMeFragment());
		fragments.add(new SettingFragment());
		// fragments.add(new WebFragment());
		getSupportFragmentManager().beginTransaction()
				.add(R.id.frame, fragments.get(2)).commit();

		zhuye = (LinearLayout) findViewById(R.id.chat_zhuye);
		contaxt = (LinearLayout) findViewById(R.id.chat_contaxt);
		xiaoxi = (LinearLayout) findViewById(R.id.chat_xiaoxi);
		footer_cooperation_container = (LinearLayout) findViewById(R.id.footer_cooperation_container);
		me = (LinearLayout) findViewById(R.id.chat_me);
		menu_foot = (LinearLayout) findViewById(R.id.menu_foot);
		index_image = (ImageView) findViewById(R.id.index_image);
		footer_cooperation_icon = (ImageView) findViewById(R.id.footer_cooperation_icon);
		contaxt_image = (ImageView) findViewById(R.id.contaxt_image);
		xiaoxi_image = (ImageView) findViewById(R.id.xiaoxi_image);
		me_image = (ImageView) findViewById(R.id.me_image);
		// drop = (WaterDrop)findViewById(R.id.drop);
		drop = (TextView) findViewById(R.id.drop);
		zhuye_text = (TextView) findViewById(R.id.index_text);
		xiaoxi_Text = (TextView) findViewById(R.id.xiaoxi_Text);
		me_Text = (TextView) findViewById(R.id.me_Text);
		contaxt_text = (TextView) findViewById(R.id.contaxt_text);
		footer_cooperation_text = (TextView) findViewById(R.id.footer_cooperation_text);

		zhuye.setOnClickListener(new MyOnClickListener(0));// 主页
		xiaoxi.setOnClickListener(new MyOnClickListener(1));// 消息
		footer_cooperation_container
				.setOnClickListener(new MyOnClickListener(2));// 协作
		contaxt.setOnClickListener(new MyOnClickListener(3));// 同事
		me.setOnClickListener(new MyOnClickListener(4));// 关于我

		index_image.setOnClickListener(new MyOnClickListener(0));
		xiaoxi_image.setOnClickListener(new MyOnClickListener(1));
		footer_cooperation_icon.setOnClickListener(new MyOnClickListener(2));
		contaxt_image.setOnClickListener(new MyOnClickListener(3));
		me_image.setOnClickListener(new MyOnClickListener(4));

		zhuye_text.setOnClickListener(new MyOnClickListener(0));
		xiaoxi_Text.setOnClickListener(new MyOnClickListener(1));
		footer_cooperation_text.setOnClickListener(new MyOnClickListener(2));
		contaxt_text.setOnClickListener(new MyOnClickListener(3));
		me_Text.setOnClickListener(new MyOnClickListener(4));
		// 默认显示第一页
		setSelect(0);
		tabSelect(0);
		// 注册广播
		receiver = new MyMessageReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(AppContext.MESSAGE_DAISHENPI);
		filter.addAction(AppContext.MESSAGE_DAIBANRENWU);
		filter.addAction(AppContext.MESSAGE_RICHENG_EVENT);
		filter.addAction(AppContext.MESSAGE_CHATMESSAGE);
		filter.addAction(AppContext.MESSAGE_SYSTEM);
		filter.addAction(AppContext.UPDATE_USER_ICON);
		filter.addAction(AppContext.MESSAGE_SYSTEM_NUM);
		filter.addAction(AppContext.TASK_NUM);
		filter.addAction(AppContext.DAISHENPI_NUM);
		filter.addAction(AppContext.CAOGAO_NUM);
		filter.addAction(AppContext.EVENT_NUM);
		filter.addAction(AppContext.MESSAGE_CHAT_NUM);
		filter.addAction(AppContext.OPEN_FILE);
		filter.addAction(AppContext.WEB_TO_MENU);
		filter.addAction(AppContext.GET_WEIXIN_LOGIN);
		registerReceiver(receiver, filter);

		//setChatMessageNum();
		try {
			setMessageNum();
			setChatMessageNum();
		} catch (DbException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 设置未读消息条数
	 * 
	 * @throws DbException
	 */
	private void setMessageNum() throws DbException {
		// 设置消息数量
		MessageDB db = new MessageDB(mContext, UserManager.getManager()
				.getUser().userId + "message");
		long messnum = db.getNewMessageNum();
		DraftBoxDB db2 = new DraftBoxDB(mContext, UserManager.getManager()
				.getUser().userId + "box.db");
		long draftnum = db2.getNewDraftBoxNum();
		TaskDB db3 = new TaskDB(mContext,
				UserManager.getManager().getUser().userId + "chat");
		long tasknum = db3.getNewTaskNum();
		ApprovalDB db4 = new ApprovalDB(mContext, UserManager.getManager()
				.getUser().userId + "chat");
		long approvalnum = db4.getNewApprovalNum();
		EventDB db5 = new EventDB(mContext,
				UserManager.getManager().getUser().userId + "chat");
		long eventnum = db5.getNewEventNum();
		ChatMessageDB db6 = new ChatMessageDB(mContext, UserManager
				.getManager().getUser().userId + "chat");
		long atnum = db6.getNewChatMessageNum();

		AppContext.dspnum = (int) approvalnum;
		AppContext.rwnum = (int) tasknum;
		AppContext.mesnum = (int) messnum;
		AppContext.eventnum = (int) eventnum;
		AppContext.atnum = (int) atnum;
		// 消息提示数量由很多种类型的消息组成的
		num = messnum + draftnum + tasknum + approvalnum + eventnum + atnum;
	}
	private void setChatMessageNum() {
		int countTotal = (int) (num + EMChatManager.getInstance()
				.getUnreadMsgsCount());
		if (countTotal > 0) {
			drop.setVisibility(View.VISIBLE);
			if (countTotal > 99) {
				drop.setText("99");
			} else {
				drop.setText("" + countTotal);
			}
		} else {
			drop.setVisibility(View.GONE);
		}
	}
	public class MyOnClickListener implements View.OnClickListener {
		private int index = 0;

		public MyOnClickListener(int i) {
			index = i;
		}

		@Override
		public void onClick(View v) {
			tabSelect(index);
		}
	};

	/**
	 * 选择
	 * 
	 * @param index
	 */
	private void tabSelect(int index) {
		if (currentTab == index) {
			return;
		}
		// 设置选择后的效果
		setSelect(index);
		// 获得 将要展示的fragment
		Fragment fragment = fragments.get(index);
		FragmentTransaction ft = this.getSupportFragmentManager()
				.beginTransaction();
		if (currentTab < 0)
			currentTab = 0;
		fragments.get(currentTab).onPause(); // 暂停当前tab
		if (fragment.isAdded()) {
			fragment.onResume(); // 启动目标tab的onResume()
		} else {
			ft.add(R.id.frame, fragment);
		}
		ft.commit();
		showTab(index); // 显示目标tab

	}

	/**
	 * 切换tab
	 * 
	 * @param idx
	 */
	@SuppressLint("Recycle")
	private void showTab(int idx) {
		for (int i = 0; i < fragments.size(); i++) {
			Fragment fragment = fragments.get(i);
			FragmentTransaction ft = this.getSupportFragmentManager()
					.beginTransaction();
			ft.setCustomAnimations(R.anim.frag_slide_in_left,
					R.anim.frag_slide_out_right);
			getSupportFragmentManager().beginTransaction().addToBackStack(null);
			if (idx == i) {
				ft.show(fragment);
			} else {
				ft.hide(fragment);
			}
			ft.commit();
		}
		currentTab = idx;
		invalidateOptionsMenu();
	}

	/**
	 * 设置图标效果
	 * 
	 * @param index
	 */
	public void setSelect(int index) {
		switch (index) {
		case 0:// home
			xiaoxi_Text.setTextColor(getResources().getColor(R.color.hui));
			xiaoxi_image
					.setImageResource(R.drawable.chater_index_message_transp);
			me_Text.setTextColor(getResources().getColor(R.color.hui));
			me_image.setImageResource(R.drawable.chatter_index_aboutme_transp);

			footer_cooperation_icon
					.setImageResource(R.drawable.footer_tab_cooperation_nor);
			footer_cooperation_text.setTextColor(getResources().getColor(
					R.color.hui));

			contaxt_text.setTextColor(getResources().getColor(R.color.hui));
			contaxt_image
					.setImageResource(R.drawable.chatter_index_tongshi_transp);

			zhuye_text.setTextColor(getResources().getColor(
					R.color.dingbu_color));
			index_image.setImageResource(R.drawable.chatter_index_zhuye);
			break;
		case 1:// message
			zhuye_text.setTextColor(getResources().getColor(R.color.hui));
			index_image.setImageResource(R.drawable.chatter_index_zhuye_transp);
			me_Text.setTextColor(getResources().getColor(R.color.hui));
			me_image.setImageResource(R.drawable.chatter_index_aboutme_transp);

			footer_cooperation_icon
					.setImageResource(R.drawable.footer_tab_cooperation_nor);
			footer_cooperation_text.setTextColor(getResources().getColor(
					R.color.hui));

			contaxt_text.setTextColor(getResources().getColor(R.color.hui));
			contaxt_image
					.setImageResource(R.drawable.chatter_index_tongshi_transp);
			xiaoxi_Text.setTextColor(getResources().getColor(
					R.color.dingbu_color));
			xiaoxi_image.setImageResource(R.drawable.chater_index_message);
			break;
		case 2:// message
			zhuye_text.setTextColor(getResources().getColor(R.color.hui));
			index_image.setImageResource(R.drawable.chatter_index_zhuye_transp);
			me_Text.setTextColor(getResources().getColor(R.color.hui));
			me_image.setImageResource(R.drawable.chatter_index_aboutme_transp);

			contaxt_text.setTextColor(getResources().getColor(R.color.hui));
			contaxt_image
					.setImageResource(R.drawable.chatter_index_tongshi_transp);

			xiaoxi_Text.setTextColor(getResources().getColor(R.color.hui));
			xiaoxi_image
					.setImageResource(R.drawable.chater_index_message_transp);

			footer_cooperation_icon
					.setImageResource(R.drawable.footer_tab_cooperation_hover);
			footer_cooperation_text.setTextColor(getResources().getColor(
					R.color.dingbu_color));
			break;
		case 3:
			zhuye_text.setTextColor(getResources().getColor(R.color.hui));
			index_image.setImageResource(R.drawable.chatter_index_zhuye_transp);
			xiaoxi_Text.setTextColor(getResources().getColor(R.color.hui));

			xiaoxi_image
					.setImageResource(R.drawable.chater_index_message_transp);
			footer_cooperation_icon
					.setImageResource(R.drawable.footer_tab_cooperation_nor);
			footer_cooperation_text.setTextColor(getResources().getColor(
					R.color.hui));

			me_Text.setTextColor(getResources().getColor(R.color.hui));
			me_image.setImageResource(R.drawable.chatter_index_aboutme_transp);
			contaxt_text.setTextColor(getResources().getColor(
					R.color.dingbu_color));
			contaxt_image.setImageResource(R.drawable.chatter_index_tongshi);
			break;
		case 4:
			zhuye_text.setTextColor(getResources().getColor(R.color.hui));
			index_image.setImageResource(R.drawable.chatter_index_zhuye_transp);
			xiaoxi_Text.setTextColor(getResources().getColor(R.color.hui));
			xiaoxi_image
					.setImageResource(R.drawable.chater_index_message_transp);

			footer_cooperation_icon
					.setImageResource(R.drawable.footer_tab_cooperation_nor);
			footer_cooperation_text.setTextColor(getResources().getColor(
					R.color.hui));

			contaxt_text.setTextColor(getResources().getColor(R.color.hui));
			contaxt_image
					.setImageResource(R.drawable.chatter_index_tongshi_transp);
			me_Text.setTextColor(getResources().getColor(R.color.dingbu_color));
			me_image.setImageResource(R.drawable.chatter_index_aboutme);
			break;
		}
	}

	@Override
	public void onBackPressed() {
		DialogUtils.Exit(mContext);
	}

	/**
	 * 初始化消息推送，定位上传参数
	 */
	public void initPushAndLocat() {

		ConfigManager configManager = ConfigManager.getInstance();

		if (configManager.isAllowLocation()) {// 如果定位开启 就 开启定位
			Intent service = new Intent(this, DingWeiService.class);
			startService(service);
		}
		if (configManager.isAllowPush()) {
			CloudCCPushManager.getInstance().startPushWork();
		} else {
			CloudCCPushManager.getInstance().stopPushWork();
		}
		// 后台绑定bingding
		Intent service = new Intent(this, BindingService.class);
		startService(service);
	}

	/**
	 * 主页广播
	 * 
	 * @author Administrator
	 * 
	 */
	class MyMessageReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			try {
				String action = intent.getAction();
				if (action.equals(AppContext.MESSAGE_SYSTEM)
						|| action.equals(AppContext.MESSAGE_CHATMESSAGE)
						|| action.equals(AppContext.MESSAGE_DAISHENPI)
						|| action.equals(AppContext.MESSAGE_DAIBANRENWU)
						|| action.equals(AppContext.MESSAGE_RICHENG_EVENT)
						|| action.equals(AppContext.TASK_NUM)
						|| action.equals(AppContext.EVENT_NUM)
						|| action.equals(AppContext.CAOGAO_NUM)
						|| action.equals(AppContext.DAISHENPI_NUM)
						|| action.equals(AppContext.MESSAGE_CHAT_NUM)
						|| action.equals(AppContext.MESSAGE_SYSTEM_NUM)) {// 来消息广播
					try {
						setMessageNum();
						setChatMessageNum();
					} catch (DbException e) {
						e.printStackTrace();
					}
				} else if (action.equals(AppContext.SHEBEI_ZHUCE)) {// 设备注册
					// push();
				} else if (action.equals(AppContext.UPDATE_USER_ICON)) {
					menuUserLogo.setImageBitmap(AppContext.topicon);
				} else if (action.equals(AppContext.OPEN_FILE)) {
					FileUtil.openFile(context, new File(AppContext.filePath));
				} else if (action.equals(AppContext.GET_WEIXIN_LOGIN)) {
					// TODO loginWebView();// 小网页后台登陆
				} else if (action.equals(AppContext.WEB_TO_MENU)) {
					tabSelect(0);
					menu_foot.setVisibility(View.VISIBLE);
					menuHome.setSelected(true);
					menuSetting.setSelected(false);
					module_list.setItemChecked(mGroupPosition + mChildPosition
							+ 1, false);
					mGroupPosition = -1;
				}
			} catch (Exception e) {
				Tools.handle(e);
			}
		}
	}

	/**
	 * 点击侧拉 的监听
	 */
	@Override
	public boolean onChildClick(ExpandableListView parent, View v,
			int groupPosition, int childPosition, long id) {

		// 设置 主页
		menuHome.setSelected(false);
		menuSetting.setSelected(false);
		menu_foot.setVisibility(View.VISIBLE);
		AppContext.iscomeMenu = true;
		MenuModel menuItem = mMenuAdapter.getGroup(groupPosition);
		MenuTabModel menuTab = mMenuAdapter.getChild(groupPosition,
				childPosition);
		AppContext.indexUrl = UrlManager.getRootUrl()
				+ UrlTools.getModuleUrl(menuItem.id, menuItem.label);
		AppContext.urlString = UrlManager.getRootUrl()
				+ UrlTools.getTabsUrl(menuTab, menuItem);
		menuHome.setSelected(true);
		menuSetting.setSelected(false);
		module_list.setItemChecked(mGroupPosition + mChildPosition + 1, false);
		mGroupPosition = -1;
		MenuManager.getInstance().enterMenuDetailOrList(menuTab, this);
		return true;
	}

	/**
	 * 获得菜单成功
	 * 
	 * @param event
	 */
	public void onEventMainThread(MenuFillEvent event) {
		if (event.isError()) {
			return;
		}
		List<MenuModel> menus = event.getData().data;
		MenuManager.getInstance().filterMenus(menus);
		CacheManager.getInstance().cacheMenu(menus);
		fillMenu(true, menus);
		
	}

	private void fillMenu(boolean refresh, List<MenuModel> menus) {

		int expId = 0;
		ccMenu =menus.get(0);
		for (int i = 0; i < menus.size(); i++) {
			MenuModel menuItem = menus.get(i);
			if (StringUtils.equals(menuItem.state, "1")) {// 默认打开
				ccMenu = menuItem;
				expId = i;
			}
		}
		if (refresh || mMenuAdapter == null) {
			mMenuAdapter = new MyMenuAdapter(menus, this);
		}
		module_list.setAdapter(mMenuAdapter);
		module_list.setGroupIndicator(null);
		module_list.setOnChildClickListener(this);
		module_list.setOnGroupClickListener(groupListener);
		module_list.expandGroup(expId);

		// 通知主页更新
		Fragment fragment=null;
		try {
			fragment = fragments.get(0);
		} catch (Exception e) {
		}
		if (null!=fragment&&fragment instanceof MainUIFragment && fragment.isResumed()
				&& refresh) {
			((MainUIFragment) fragment).initData();
		}

	}

	private OnGroupClickListener groupListener = new OnGroupClickListener() {

		@Override
		public boolean onGroupClick(ExpandableListView parent, View v,
				int groupPosition, long id) {
			if (sign == -1) {
				// 展开被选的group
				module_list.expandGroup(groupPosition);
				sign = groupPosition;
			} else if (sign == groupPosition) {
				module_list.collapseGroup(sign);
				sign = -1;
			} else {
				module_list.collapseGroup(sign);
				// 展开被选的group
				module_list.expandGroup(groupPosition);
				sign = groupPosition;
			}
			return true;
		}
	};
	private int mActivityFrom;

	@Override
	public void register() {
		EventEngine.register(this);
	}

	@Override
	public void unRegister() {
		EventEngine.uregister(this);
	}

	@Override
	protected void onDestroy() {
		EventEngine.uregister(this);
		try {
			unregisterReceiver(receiver);
		} catch (Exception e) {
			Tools.handle(e);
		}
		super.onDestroy();
		

		try {
			// 处理测试数据
			if (RunTimeManager.getInstance().isTestModel()) {
				AppManager.getInstance().clearTestModel();
			}
		} catch (Exception e) {
			Tools.handle(e);
		}
		
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.shouye_menu:// 首页
			tabSelect(0);
			menu_foot.setVisibility(View.VISIBLE);
			menu.toggle();
			menuHome.setSelected(true);
			menuSetting.setSelected(false);
			int numberOfGroupThatIsOpened = 0;
			for (int i = 0; i < mGroupPosition; i++) {
				if (module_list.isGroupExpanded(i)) {
					numberOfGroupThatIsOpened += mMenuAdapter
							.getChildrenCount(i);
				}
			}
			module_list.setItemChecked(mGroupPosition + mChildPosition
					+ numberOfGroupThatIsOpened + 1, false);
			mGroupPosition = -1;
			break;
		case R.id.shezhi_menu:
			menu_foot.setVisibility(View.GONE);
			tabSelect(5);
			menuHome.setSelected(false);
			menuSetting.setSelected(true);
			int numberOfGroupThatIsOpened2 = 0;
			for (int i = 0; i < mGroupPosition; i++) {
				if (module_list.isGroupExpanded(i)) {
					numberOfGroupThatIsOpened2 += mMenuAdapter
							.getChildrenCount(i);
				}
			}
			module_list.setItemChecked(mGroupPosition + mChildPosition
					+ numberOfGroupThatIsOpened2 + 1, false);
			menu.toggle();
			mGroupPosition = -1;
			break;

		case R.id.userimg:
		case R.id.phototext:
			showSelectImg();
			break;
		default:
			break;
		}
	}

	private void loginWebView() {
		webview = (WebView) findViewById(R.id.loginwebview);
		WebSettings webSettings = webview.getSettings();
		webSettings.setAllowFileAccess(true);
		webSettings.setJavaScriptEnabled(true);
		webview.setWebViewClient(new WebViewClient() {
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				view.loadUrl(url);
				return true;
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				int end = url.indexOf(";");
				String name;
				if (end != -1) {
					name = url.substring(0, end);
				} else {
					name = url;
				}
				if (name.equals(UrlTools.weixinUrl + UrlTools.loginWeb)
						|| name.equals(UrlTools.weixinUrl + "/main.action")
						|| name.equals(UrlTools.weixinUrl
								+ "/WeiXin_index.action")) {
					AppContext.islogining = true;
				}
				super.onPageFinished(view, url);
			}

			@Override
			public void onLoadResource(WebView view, String url) {
				super.onLoadResource(view, url);
			}
		});
		webview.loadUrl(UrlManager.getBindingUrl()
				+ RunTimeManager.getInstance().getServerBinding());
	}

	/**
	 * 显示头像图片选择
	 */
	private void showSelectImg() {
		Intent intent = new Intent(MainUIActivity.this,
				SelectPictureActivity.class);
		startActivityForResult(intent, 70);
	}

	/**
	 * 裁剪图片方法实现
	 * 
	 * @param uri
	 */
	private void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		// 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 150);
		intent.putExtra("outputY", 150);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, 3);
	}

	@Override
	protected void onResume() {
		super.onResume();
	try {
		setMessageNum();
		setChatMessageNum();
	} catch (Exception e) {
	}
		// 注册 消息监听
		 EMChatManager.getInstance().registerEventListener(
		 this,
		 new EMNotifierEvent.Event[] {
		 EMNotifierEvent.Event.EventNewMessage,
		 EMNotifierEvent.Event.EventOfflineMessage,
		 EMNotifierEvent.Event.EventConversationListChanged });

	}

	@Override
	protected void onStop() {
		// 取消消息监听
		EMChatManager.getInstance().unregisterEventListener(this);
		super.onStop();
	}

	/**
	 * 消息接收到的时候
	 * 
	 * @param arg0
	 */
	@Override
	public void onEvent(EMNotifierEvent event) {
		switch (event.getEvent()) {
		case EventNewMessage: // 普通消息
		{
			EMMessage message = (EMMessage) event.getData();
			IMHelper.getInstance().getNotifier().onNewMsg(message);
			break;
		}

		case EventOfflineMessage: {
			break;
		}

		case EventConversationListChanged: {

			break;
		}
		default:
			break;
		}
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				setChatMessageNum();
				refreshMessage();

			}
		});

	}

	private void refreshMessage() {
		if (currentTab == 1) {
			((MainMessageFragment) fragments.get(1)).Imset();
		}
	}

	/**
	 * 登录聊天
	 */
	private void loginIM() {
		// 获取用户名
		UserModel user = UserManager.getManager().getUser();
		final String hxUserName = ContactsManager.getInstance()
				.encodeHXuserName(user.userId);
		LogUtils.d("imchat", "登录帐号:"+hxUserName);
		// 使用userId登录
		if (IMHelper.getInstance().isLoggedIn()
				&& StringUtils.equals(IMHelper.getInstance()
						.getCurrentUsernName(), hxUserName)) {
			LogUtils.d("imchat", "已经登录了。。");
			loadIMData();
			return;
		}
		PreferenceManager.getInstance().removeCurrentUserInfo();
		
		EMChatManager.getInstance().login(hxUserName, "szydcloudcc",
				new EMCallBack() {

					@Override
					public void onSuccess() {
						LogUtils.d("imchat", "登录成功。。");
						// 登陆成功，保存用户名
						IMHelper.getInstance().setCurrentUserName(hxUserName);
						// 注册群组和联系人监听
						IMHelper.getInstance()
								.registerGroupAndContactListener();

						// ** 第一次登录或者之前logout后再登录，加载所有本地群和回话
						// ** manually load all local groups and


						// 更新当前用户的nickname 此方法的作用是在ios离线推送时能够显示用户nick
						// boolean updatenick =
						// EMChatManager.getInstance().updateCurrentUserNick(
						// DemoApplication.currentUserNick.trim());
						// if (!updatenick) {
						// Log.e("LoginActivity",
						// "update current user nick fail");
						// }
						// 异步获取当前用户的昵称和头像(从自己服务器获取，demo使用的一个第三方服务)
						// DemoHelper.getInstance().getUserProfileManager().asyncGetCurrentUserInfo();
						// 获取cloucc服务器的通讯录
						loadIMData();
					}

					@Override
					public void onProgress(int progress, String status) {
					}

					@Override
					public void onError(final int code, final String message) {
//						LogUtils.d("imchat", "登录失败:"+hxUserName);
//						runOnUiThread(new Runnable() {
//							public void run() {
//								Toast.makeText(
//										getApplicationContext(),
//										getString(R.string.Login_failed)
//												+ message, Toast.LENGTH_SHORT)
//										.show();
//							}
//						});
					}
				});
	}
	
	private void loadIMData(){
		LogUtils.d("imchat", "开始loading。。");
		EMGroupManager.getInstance().loadAllGroups();
		EMChatManager.getInstance().loadAllConversations();
		long queryCount = OrmManager.getManager().getOrm().queryCount(CoworkerEntity.class);
		if (queryCount<5) {
			ContactsManager.getInstance().syncContactes();
		}
	}
	
	/**
	 * 获得 ccmenu 子菜单列表
	 * 
	 * @return
	 */
	public MenuModel getCCMenuItems() {
		return ccMenu;
	}

}
